package com.itheima;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Enumeration;

public class StudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取相关的信息
        String name = req.getParameter("username");
        String age = req.getParameter("age");
        String score = req.getParameter("score");
        //将这些信息进行封装打印
        String realPath = getServletContext().getRealPath("student.txt");
        System.out.println(realPath);
        BufferedWriter bw = new BufferedWriter(new FileWriter(realPath));
        bw.write(name + "," + age + "," + score);
        bw.newLine();
        bw.flush();
        bw.close();


        //获取当前servlet的config
        ServletConfig servletConfig = getServletConfig();
        //获取当前config中的所有的属性的名字,也就是我在web.xml中定义init-param中的param-name
        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
        //对每一个param-name进行遍历,对其中的每一个进行相关的操作,这部分的遍历原理和迭代器原理相同
        while (initParameterNames.hasMoreElements()){
            String s = initParameterNames.nextElement();
            //获取每一个param-name后,再调用获取属性值的方法,获取属性值
            String initParameter = servletConfig.getInitParameter(s);
            //进行打印
            System.out.println(initParameter);
        }
        //全局上下文
        ServletContext servletContext = getServletContext();
        servletContext.setAttribute("class","zhangsan");
        System.out.println(servletContext.getAttribute("class"));


        //对网页进行响应
        PrintWriter pw = resp.getWriter();
        pw.println("Everything is OK");
        pw.flush();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
